package sennetworkserver;

import java.net.ServerSocket;
import java.net.Socket;

public class NetworkServer implements Runnable {
	
	public ServerSocket serverSocket;
	public Thread networkThread;
	private int port = 0;
	private boolean connected = false;
	private ConnectionHandler handler;
	public LaneStore laneStore;
	
	public NetworkServer(int port)  {
		networkThread = new Thread(this);
		networkThread.start();
		this.port = port;
	}

	@Override
	public void run() {
		try {
			serverSocket = new ServerSocket(port);
			System.out.println("Server is accepting connection on port: " + port);
			while(true) {
				if(!connected){
					Socket s = serverSocket.accept();
					if(s.isConnected()) {
						handler = new ConnectionHandler(s);
						System.out.println("Client connected");
						connected = true;
					}					
				} else {
					if(!handler.connection.isConnected()) {
						connected = false;
					}				
					Thread.sleep(500);
				}
				
			}
		} catch(Exception ex) {
			System.out.println(ex.toString());
		}
	}
}
